package nut.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import nut.common.handler.exceptionhandler.MyException;
import nut.common.utils.Result;
import nut.entity.*;
import nut.entity.vo.PositionVO;
import nut.entity.vo.RecruitWithScoreVo;
import nut.service.EnterpriseService;
import nut.service.RecruitService;
import nut.service.UserService;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author 郜宇博
 * @since 2021-12-19
 */
@Api(tags = "求职者Api")
@RestController
@RequestMapping("api")
public class UserController {
    private final UserService userService;
    private final RecruitService recruitService;
    private final EnterpriseService enterpriseService;

    public UserController(UserService userService,RecruitService recruitService,EnterpriseService enterpriseService) {
        this.enterpriseService = enterpriseService;
        this.userService = userService;
        this.recruitService = recruitService;
    }
        //简历基本信息
        /*
       {
          "birthday": "2021-12-27 06:39:38",
          "email": "673354892@qq.com",
          "gender": 0,
          "marry": 0,
          "name": "郜宇博",
          "phone": "15776545893"
        }
         */
        //招聘发布
        /*
        {
          "ageRequire": "30岁左右",
          "contacts": "郜先生",
          "educationRequire": "本科以上",
          "eid": 1,
          "email": "673354892@qq.com",
          "experienceRequire": "3-5年",
          "genderRequire": 0,
          "majorRequire": "软件工程",
          "numbersLimit": 20,
          "position": "后端开发",
          "post": "java工程师",
          "salary": "5000",
          "telephone": "15776545893",
          "workplace": "黑龙江省大庆市"
        }
         */
        //简历核心
        /*
        {
          "aimJobPosition": "后端",
          "desiredWorkplace": "黑龙江",
          "experience": "3年工作经历",
          "graduated": "哈尔滨理工大学",
          "habitation": "黑龙江大庆",
          "jobCategory": "后端开发",
          "major": "软件工程",
          "personalIntroduction": "喜欢读书",
          "salaryRequire": "6000",
          "send": 0,
          "skill": "下棋"
        }
         */
    /**
     * 登录
     * @param user 用户登录信息
     * @return token
     */
    @ApiOperation("登录")
    @PostMapping("login")
    public Result loginUser(@RequestBody User user){
        String token =  userService.login(user);
        return Result.ok().data("token",token);
    }
    /**
     *  注册
     *  @param user 用户注册输入的信息
     *  @return 无
     */
    @PostMapping("register")
    @ApiOperation("注册")
    public Result registerUser(@RequestBody User user){
        userService.register(user);
        return Result.ok().message("注册成功");
    }
    /**
     * 通过token获取用户信息
     * @param request http请求
     * @return 用户信息
     */
    @ApiOperation("通过token获取用户信息")
    @GetMapping("userInfo")
    public Result getUserInfo(HttpServletRequest request){
        User user  = userService.getUserByToken(request);
        return Result.ok().data("userInfo",user);
    }
    /**
     * 添加简历基本信息
     * @param resumeBaseInfo 简历基本信息
     * @return 简历id
     */
    @ApiOperation("添加简历基本信息")
    @PostMapping("resumeBaseInfo")
    public Result addResumeBaseInfo(@RequestBody ResumeBaseInfo resumeBaseInfo,HttpServletRequest httpServletRequest){
        User user = userService.getUserByToken(httpServletRequest);
        int resumeId = userService.addResumeBaseInfo(resumeBaseInfo,user.getUid());
        return Result.ok().data("resumeId",resumeId);
    }
    /**
     * 添加简历核心信息
     * @param resumeCoreInfo 简历核心信息
     * @return 简历id
     */
    @ApiOperation("添加简历核心信息")
    @PostMapping("resumeCoreInfo/{resumeId}")
    public Result addResumeCoreInfo(@RequestBody Resume resumeCoreInfo,
                                    @ApiParam(name = "resumeId", value = "简历id",required = true) @PathVariable int resumeId){
        boolean flag = userService.addResumeCoreInfo(resumeCoreInfo, resumeId);
        return flag?Result.ok().data("resumeId",resumeId):Result.error().message("添加简历关键信息失败");
    }
    /**
     * 投递简历
     * @return flag
     */
    @ApiOperation("投递简历")
    @PostMapping("submitResume/{recruitId}")
    public Result submitResume(@ApiParam(name = "recruitId", value = "招聘id",required = true) @PathVariable int recruitId,
                               HttpServletRequest httpServletRequest){
        long startTime = System.currentTimeMillis();
        User user = userService.getUserByToken(httpServletRequest);
        int resumeId;
        if ((resumeId= user.getResumeId()) != 0){
            boolean flag = userService.submitResume(recruitId,resumeId,user.getUid());
            long endTime = System.currentTimeMillis();
            //性能测试
            System.out.println("用时="+(endTime-startTime)+"毫秒");
            return flag? Result.ok().message("投递简历成功"):Result.error().message("简历投递失败");
        }
        return Result.error().message("未填写本人简历");
    }

    /**
     * 分页指定公司的所有招聘
     * @param current 当前页
     * @param limit 每页记录数
     * @param eid 企业id
     * @return recruitPage
     */
    @ApiOperation("分页获取指定公司招聘")
    @GetMapping("pageRecruits/{current}/{limit}/{eid}")
    public Result getPageRecruitsByEid(@ApiParam(name = "current", value = "当前页码",required = true) @PathVariable Long current,
                                  @ApiParam(name = "limit", value = "一页记录数",required = true) @PathVariable Long limit,
                                   @ApiParam(name = "eid", value = "企业id",required = true) @PathVariable Integer eid){

        Page<Recruit> page = new Page<>(current,limit);
        IPage<Recruit> recruitPage = recruitService.pageListRecruits(page, eid);
        recruitPage.setTotal(recruitPage.getRecords().size());
        return Result.ok().data("recruitPage",recruitPage);
    }
    /**
     * 分页获取所有招聘
     * @param current 当前页
     * @param limit 每页记录数
     * @return recruitPage
     */
    @ApiOperation("分页获取所有招聘")
    @GetMapping("pageRecruits/{current}/{limit}")
    public Result getPageRecruits(@ApiParam(name = "current", value = "当前页码",required = true) @PathVariable Long current,
                                   @ApiParam(name = "limit", value = "一页记录数",required = true) @PathVariable Long limit){

        Page<Recruit> page = new Page<>(current,limit);
        IPage<Recruit> recruitPage = recruitService.pageListRecruits(page);
        recruitPage.setTotal(recruitPage.getRecords().size());
        return Result.ok().data("recruitPage",recruitPage);
    }
    /**
     * 获取指定二级岗位的所有招聘
     * @param current 当前页
     * @param limit 每页记录数
     * @param post 二级分类
     * @return recruitPage
     */
    @ApiOperation("获取指定二级岗位的所有招聘")
    @GetMapping("pageRecruitsByPost/{current}/{limit}/{post}")
    public Result getPageRecruitsByPost(@ApiParam(name = "current", value = "当前页码", required = true) @PathVariable Long current,
                                        @ApiParam(name = "limit", value = "一页记录数", required = true) @PathVariable Long limit,
                                        @ApiParam(name = "post", value = "二级岗位分类", required = true) @PathVariable String post){

        Page<Recruit> page = new Page<>(current,limit);
        IPage<Recruit> recruitPage = recruitService.getPageRecruitsByPost(page, post);
        recruitPage.setTotal(recruitPage.getRecords().size());
        return Result.ok().data("recruitPage",recruitPage);
    }
    /**
     * 分级获取所有岗位
     * @return positionList
     */
    @ApiOperation("分级获取所有岗位")
    @GetMapping("positionList")
    public Result positionListByLevel(){
        List<PositionVO> positionList = recruitService.getRecruitsByLevel();
        return Result.ok().data("positionList",positionList);
    }

    /**
     * 获取所有招聘，并匹配自己的简历打分
     * @return recruitList
     */
    @ApiOperation("获取所有招聘，并匹配自己的简历打分")
    @GetMapping("matchResume")
    public Result matchResume(HttpServletRequest httpServletRequest){
        long startTime = System.currentTimeMillis();
        //获取uid
        User user  = userService.getUserByToken(httpServletRequest);
        int resumeId = user.getResumeId();
        if (resumeId != 0){
            //获取所有招聘（有分）
            List<RecruitWithScoreVo> recruitList = userService.getRecruitsWithScore(resumeId);
            //排序
            recruitList.sort(Comparator.comparingDouble((RecruitWithScoreVo x) -> Double.parseDouble(x.getScore())).reversed());
            long endTime = System.currentTimeMillis();
            //性能测试
            System.out.println("用时="+(endTime-startTime)+"毫秒");
            return Result.ok().data("recruitList",recruitList);
        }
        throw new MyException(20001,"未填写本人简历");
    }
    /**
     * 查询本人是否填写过简历
     * @return flag
     */
    @ApiOperation("查询本人是否填写过简历")
    @GetMapping("hasResume")
    public Result hasResume(HttpServletRequest httpServletRequest){
        User user  = userService.getUserByToken(httpServletRequest);
        if (user == null){
            throw new MyException(20001,"请登录");
        }
        boolean flag = false;
        if (user.getResumeId() != 0){
            flag = true;
        }
        return Result.ok().data("hasResume",flag);
    }
    /**
     * @param resumeBaseInfo 简历基础信息
     * @return flag
     */
    @ApiOperation("修改简历基础信息")
    @PutMapping("resumeBaseInfo")
    public Result updateResumeBaseInfo(HttpServletRequest httpServletRequest,
                                   @ApiParam("简历基础信息") @RequestBody ResumeBaseInfo resumeBaseInfo){
        int resumeId = userService.getUserByToken(httpServletRequest).getResumeId();
        boolean flag = userService.updateResumeBaseInfo(resumeBaseInfo,resumeId);
        return flag?Result.ok().message("更新简历基础信息成功"):Result.error().message("更新失败");
    }
    /**
     * @param resumeCoreInfo 简历核心信息
     * @return flag
     */
    @ApiOperation("修改简历核心信息")
    @PutMapping("resumeCoreInfo")
    public Result updateResumeCoreInfo(HttpServletRequest httpServletRequest,
                                   @ApiParam("简历核心信息") @RequestBody Resume resumeCoreInfo){
        int resumeId = userService.getUserByToken(httpServletRequest).getResumeId();
        boolean flag = userService.updateResumeCoreInfo(resumeCoreInfo,resumeId);
        return flag?Result.ok().message("更新简历基础信息成功"):Result.error().message("更新失败");
    }

    /**
     * 获取简历所有信息
     * @return resumeInfo
     */
    @ApiOperation("获取简历所有信息,三种")
    @GetMapping("myResume")
    public Result getMyResumeAllInfo(HttpServletRequest httpServletRequest){
        //获取resumeId
        int resumeId = userService.getUserByToken(httpServletRequest).getResumeId();
        if (resumeId != 0){
            //获取简历所有信息
            Map<String,Object> resumeInfo = enterpriseService.getResumeAllInfo(resumeId);
            return Result.ok().data(resumeInfo);
        }
        return Result.error().message("个人简历未填写");
    }
}

